//
//  YFCompareLineChart.m
//  SquashSpark
//
//  Created by Coollang on 2017/12/2.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFCompareLineChart.h"

static const CGFloat kAnimationDuration = 0.5f;

@interface YFCompareLineChart()

@property (strong, nonatomic) UIView *pview;
@property (strong, nonatomic) UIView *pHLine;
@property (strong, nonatomic) UIView *pVLine;
@property (strong, nonatomic) UIView *bview;
@property (strong, nonatomic) UIView *bHLine;
@property (strong, nonatomic) UIView *bVLine;

@end

@implementation YFCompareLineChart

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.lineChartView = [[LineChartView alloc] initWithFrame:frame];
        [self addSubview:self.lineChartView];
        [self.lineChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        self.lineChartView = [[LineChartView alloc] init];
        [self addSubview:self.lineChartView];
        [self.lineChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    return self;
}


#pragma mark - 设置样式
- (void)setUpLineChartView {
    LineChartView *chartView = _lineChartView;
    chartView.delegate = self;
    chartView.descriptionText = @"";
    chartView.noDataText = @"Not select action model";
    chartView.legend.enabled = NO;
    chartView.scaleYEnabled = NO;//取消Y轴缩放
    chartView.scaleXEnabled = NO;//取消X轴缩放
    chartView.scaleEnabled = NO;// 缩放
    chartView.doubleTapToZoomEnabled = NO;//取消双击缩放
    chartView.dragDecelerationEnabled = NO;//拖拽后是否有惯性效果
    
    UIColor *color = kTLightGray999;
    //X轴设置
    ChartXAxis *xAxis = chartView.xAxis;
    xAxis.enabled = YES;
    xAxis.drawGridLinesEnabled = NO;//不绘制网络线
    xAxis.axisLineColor = color;// x 轴的网络线颜色
    xAxis.labelTextColor = color;
    xAxis.labelPosition = XAxisLabelPositionBottom;
    xAxis.drawAxisLineEnabled = NO;
    
    //左边Y轴设置
    ChartYAxis *leftAxis = chartView.leftAxis;
    leftAxis.enabled = YES;
    leftAxis.labelTextColor = color;
    leftAxis.drawGridLinesEnabled = YES;
    leftAxis.drawAxisLineEnabled = NO;
    leftAxis.drawZeroLineEnabled = NO;
    leftAxis.labelCount = 5;
    leftAxis.forceLabelsEnabled = YES;
    leftAxis.drawTopYLabelEntryEnabled = YES;
    
    //右边Y轴设置
    ChartYAxis *rightAxis = chartView.rightAxis;
    rightAxis.enabled = YES;
    rightAxis.drawLabelsEnabled = NO;
    rightAxis.drawGridLinesEnabled = NO;
    rightAxis.drawAxisLineEnabled = NO;
    rightAxis.labelCount = 5;
    rightAxis.forceLabelsEnabled = YES;
    
    [self setYAixMaxValue:90 MinValue:-90];
}

- (void)setYAixMaxValue:(double)maxValue MinValue:(double)minValue {
    maxValue = MAX(fabs(maxValue), fabs(minValue));
    maxValue = maxValue <= 85 ? 90:100;
    minValue = -maxValue;
    
    ChartYAxis *leftAxis = _lineChartView.leftAxis;
    leftAxis.axisMaximum = maxValue;
    leftAxis.axisMinimum = minValue;
    leftAxis.axisMaxValue = maxValue;
    leftAxis.axisMinValue = minValue;
    
    ChartYAxis *rightAxis = _lineChartView.rightAxis;
    rightAxis.axisMaximum = maxValue;
    rightAxis.axisMinimum = minValue;
    rightAxis.axisMaxValue = maxValue;
    rightAxis.axisMinValue = minValue;
}

- (void)drawLineWithTemplate:(YFThreeDTemplate *)threeDTemplate
                myThreeDData:(YFThreeDItem *)myThreeDData {
    
    self.lineChartView.data = [self loadLineDataWithTemplate:threeDTemplate myThreeDData:myThreeDData];
    
    // 找最大和最小值
    CGFloat temMaxVz = [[threeDTemplate.threeDItem.threeDDetailItems maxOfProperty:@"vz"] floatValue];
    CGFloat temMinVz = [[threeDTemplate.threeDItem.threeDDetailItems minOfProperty:@"vz"] floatValue];
    
    CGFloat myMaxVz = [[myThreeDData.threeDDetailItems maxOfProperty:@"vz"] floatValue];
    CGFloat myMinVz = [[myThreeDData.threeDDetailItems maxOfProperty:@"vz"] floatValue];
    
    [self setYAixMaxValue:MAX(temMaxVz, myMaxVz) MinValue:MIN(temMinVz, myMinVz)];
    
    
    // 设置双十字线
    NSInteger maxSelectValue = 0;
    NSInteger maxSelectIndex = threeDTemplate.threeDItem.maxSpeedId;
    maxSelectIndex = (maxSelectIndex == 0?threeDTemplate.threeDItem.threeDDetailItems.count / 2 : maxSelectIndex);
    YFThreeDDetailItem *selectItem = threeDTemplate.threeDItem.threeDDetailItems[maxSelectIndex];
    maxSelectValue = selectItem.vz;
    
    NSInteger maxMyValue = 0;
    NSInteger maxMyIndex = myThreeDData.maxSpeedId;
    maxMyIndex = (maxMyIndex == 0?myThreeDData.threeDDetailItems.count / 2 : maxMyIndex);
    YFThreeDDetailItem *threeDDetailItem = myThreeDData.threeDDetailItems[maxMyIndex];
    maxMyValue = threeDDetailItem.vz;
    
    ChartHighlight *myHight = [[ChartHighlight alloc] initWithX:(maxMyIndex+1)*10
                                                              y:-maxMyValue
                                                   dataSetIndex:1];
    ChartHighlight *selectHight = [[ChartHighlight alloc] initWithX:(maxSelectIndex+1)*10
                                                                  y:-maxSelectValue
                                                       dataSetIndex:0];
    
    [self.lineChartView highlightValue:myHight callDelegate:YES];
    [self.lineChartView highlightValue:selectHight callDelegate:YES];
    
}


- (LineChartData *)loadLineDataWithTemplate:(YFThreeDTemplate *)threeDTemplate
                               myThreeDData:(YFThreeDItem *)myThreeDData {
    
    NSInteger xCount;
    if (myThreeDData) {
        xCount = threeDTemplate.threeDItem.threeDDetailItems.count > myThreeDData.threeDDetailItems.count ? threeDTemplate.threeDItem.threeDDetailItems.count : myThreeDData.threeDDetailItems.count;
    }else{
        xCount = threeDTemplate.threeDItem.threeDDetailItems.count;
    }
    
    LineChartDataSet *threeTemplateDataSet = [self loadDataWithFromColor:[UIColor clearColor]
                                                                 toColor:kOrgangeLineColor
                                                                   label:@""
                                                              threeDData:threeDTemplate.threeDItem
                                                                  xCount:xCount];
    LineChartDataSet *myThreeDataSet = [self loadDataWithFromColor:[UIColor clearColor]
                                                           toColor:kGreenLineColor
                                                             label:@"-"
                                                        threeDData:myThreeDData
                                                            xCount:xCount];
    
    [_lineChartView animateWithXAxisDuration:kAnimationDuration easingOption:ChartEasingOptionLinear];
    
    if (myThreeDataSet == nil) {
        return [[LineChartData alloc] initWithDataSet:threeTemplateDataSet];
    }else{
        return [[LineChartData alloc] initWithDataSets:@[threeTemplateDataSet, myThreeDataSet]];
    }
}


/*!
 *  加载曲线数据
 *
 *  @return 绘制曲线的数据
 */
- (LineChartDataSet *)loadDataWithFromColor:(UIColor *)fromColor
                                    toColor:(UIColor *)toColor
                                      label:(NSString *)label
                                 threeDData:(YFThreeDItem *)threeDData
                                     xCount:(NSInteger)xCount {
    
    if (threeDData == nil) {
        return nil;
    }
    
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < xCount; i++) {
        YFThreeDDetailItem *modeItem;
        ChartDataEntry *entry;
        if (i < threeDData.threeDDetailItems.count) {
            modeItem = threeDData.threeDDetailItems[i];
            CGFloat value = -modeItem.vz;
            entry = [[ChartDataEntry alloc] initWithX:(i+1)*10 y:value];
            [arr addObject:entry];
        }
    }
    
    LineChartDataSet *set = [[LineChartDataSet alloc] initWithValues:arr label:label];
    //对于线的各种设置
    set.lineWidth = 4;//线宽
    set.drawValuesEnabled = NO;//不显示文字
    set.highlightEnabled = NO;//选中拐点,是否开启高亮效果(显示十字线)
    
    set.drawCirclesEnabled = NO;//是否绘制拐点
    set.cubicIntensity = .2;// 曲线弧度
    set.circleRadius = 5.0f;//拐点半径
    set.drawCircleHoleEnabled = NO;//是否绘制中间的空心
    set.mode = LineChartModeCubicBezier;// 模式为曲线模式
    [set setColor:toColor];//折线颜色
    return set;
}

- (void)clearChrtLineValues {
    [self.lineChartView clearValues];
    //十字架
    _pview.hidden = YES;
    _pHLine.hidden = YES;
    _pVLine.hidden = YES;
    _bview.hidden = YES;
    _bHLine.hidden = YES;
    _bVLine.hidden = YES;
}


#pragma mark - 处理十字架
- (void)chartValueSelected:(ChartViewBase * _Nonnull)chartView
                     entry:(ChartDataEntry * _Nonnull)entry
                 highlight:(ChartHighlight * _Nonnull)highlight {
    
    CGFloat chartW = _lineChartView.bounds.size.width - 30;
    CGFloat chartH = _lineChartView.bounds.size.height - 20;
    CGFloat lineWidth = 0.5;
    
    //创建空心圆、虚线十字架
    if (_pview == nil) {
        _pview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
        _pview.layer.cornerRadius = 5;
        _pview.layer.masksToBounds = YES;
        _pview.backgroundColor = [UIColor whiteColor];
        _pview.layer.borderWidth = 3;
        _pview.layer.borderColor = kOrgangeLineColor.CGColor;
        
        _pHLine = [[UIView alloc] initWithFrame:CGRectMake(30, 0, chartW, lineWidth)];
        _pHLine.backgroundColor = [UIColor clearColor];
        [_pHLine drawDashLineWithLength:6
                            lineSpacing:2
                              lineColor:kOrgangeLineColor
                             startPoint:CGPointMake(0, 0)
                               endPoint:CGPointMake(chartW, 0)];
        [_lineChartView addSubview:_pHLine];
        
        _pVLine = [[UIView alloc] initWithFrame:CGRectMake(30, 0, lineWidth, chartH)];
        _pVLine.backgroundColor = [UIColor clearColor];
        [_pVLine drawDashLineWithLength:6
                            lineSpacing:2
                              lineColor:kOrgangeLineColor
                             startPoint:CGPointMake(0, 0)
                               endPoint:CGPointMake(0, chartH)];
        [_lineChartView addSubview:_pVLine];
        [_lineChartView addSubview:_pview];
    }
    
    if (_bview == nil) {
        _bview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
        _bview.layer.cornerRadius = 5;
        _bview.layer.masksToBounds = YES;
        _bview.backgroundColor = [UIColor whiteColor];
        _bview.layer.borderWidth = 3;
        _bview.layer.borderColor = [UIColor orangeColor].CGColor;
        
        _bHLine = [[UIView alloc] initWithFrame:CGRectMake(30, 0, chartW, lineWidth)];
        _bHLine.backgroundColor = [UIColor clearColor];
        [_bHLine drawDashLineWithLength:6
                            lineSpacing:2
                              lineColor:kGreenLineColor
                             startPoint:CGPointMake(0, 0)
                               endPoint:CGPointMake(chartW, 0)];
        [_lineChartView addSubview:_bHLine];
        
        _bVLine = [[UIView alloc] initWithFrame:CGRectMake(30, 0, lineWidth, chartH)];
        _bVLine.backgroundColor = [UIColor clearColor];
        [_bVLine drawDashLineWithLength:6
                            lineSpacing:2
                              lineColor:kGreenLineColor
                             startPoint:CGPointMake(0, 0)
                               endPoint:CGPointMake(0, chartH)];
        [_lineChartView addSubview:_bVLine];
        [_lineChartView addSubview:_bview];
    }
    
    if (highlight.dataSetIndex == 0) {
        _pview.hidden = NO;
        _pHLine.hidden = NO;
        _pVLine.hidden = NO;
        CGPoint center = [_lineChartView pixelForValuesWithX:entry.x
                                                           y:entry.y
                                                        axis:AxisDependencyLeft];
        CGRect hFrame = _pHLine.frame;
        CGRect vFrame = _pVLine.frame;
        hFrame.origin.y = center.y;
        vFrame.origin.x = center.x;
        
        [UIView animateKeyframesWithDuration:kAnimationDuration delay:0 options:UIViewKeyframeAnimationOptionCalculationModeCubicPaced animations:^{
            _pview.center = center;
            _pHLine.frame = hFrame;
            _pVLine.frame = vFrame;
        } completion:nil];
    }else if (highlight.dataSetIndex == 1){
        _bview.hidden = NO;
        _bHLine.hidden = NO;
        _bVLine.hidden = NO;
        CGPoint center = [_lineChartView pixelForValuesWithX:entry.x
                                                           y:entry.y
                                                        axis:AxisDependencyRight];
        CGRect hFrame = _bHLine.frame;
        CGRect vFrame = _bVLine.frame;
        hFrame.origin.y = center.y;
        vFrame.origin.x = center.x;
        
        [UIView animateKeyframesWithDuration:kAnimationDuration delay:0 options:UIViewKeyframeAnimationOptionCalculationModeCubicPaced animations:^{
            _bview.center = center;
            _bHLine.frame = hFrame;
            _bVLine.frame = vFrame;
        } completion:nil];
    }
}




@end
